<template>
  <div class="app-container">
    <div style="min-height:32px;">
      <el-radio-group v-model="controller_ip" @change="controllerChange" size="small">
        <el-radio-button v-for="i in controllerList" :key="i.id" :label="i.ip_address"></el-radio-button>
      </el-radio-group>
      <!-- <el-button type="danger" class="fr" icon="el-icon-delete" @click="delete1" circle></el-button>
      <el-button type="primary" style="margin-right:10px;" class="fr" icon="el-icon-edit" @click="edit" circle>
      </el-button> -->
    </div>
    <el-divider></el-divider>
    <div v-if="shelfList.length > 0">
      <div class="flex" style="align-items: center; margin-bottom:10px;">
        <el-select v-model="filter.bus_id" style="width:100px;" clearable @change="filterShowList" placeholder="Bus筛选">
          <el-option v-for="i in busList" :key="i.value" :value="i.value">
          </el-option>
        </el-select>
        <el-select v-model="filter.line_id" style="width:140px; margin-left:5px;" clearable filterable
          @change="filterShowList" placeholder="按线别筛选">
          <el-option v-for="i in lineList" :key="i.value" :label="i.label" :value="i.value">
          </el-option>
        </el-select>
        <el-select v-model="filter.group_id" style="width:140px; margin-left:5px;" clearable filterable
          @change="filterShowList" placeholder="按工序筛选">
          <el-option v-for="i in groupList" :key="i.value" :label="i.label" :value="i.value">
          </el-option>
        </el-select>
        <div class="flex1"></div>
        <!-- <el-checkbox v-model="selectAll" @change="selectAllChange">全选/取消</el-checkbox> -->
        <el-button style="margin-left:10px;" type="success" @click="edit2">配置物料</el-button>
        <!-- <el-button type="warning" icon="el-icon-setting" @click="edit3" circle plain></el-button>
        <el-button type="danger" icon="el-icon-delete" @click="delete2" circle plain></el-button> -->
      </div>
      <div class="card" :class="{checked:i.selected}" v-for="i in showShelfList" :key="i.id">
        <el-checkbox v-model="i.selected" @change="selectedChange(i)">{{i.bus_id}} - {{i.device_address}}</el-checkbox>
        <div class="info">{{i.key_part_no}}</div>
      </div>
    </div>
    <div v-else>
      <!-- <el-button v-if="controller_ip" class="fr" type="success" @click="edit2" icon="el-icon-edit" circle plain>
      </el-button> -->
      <p style="color:#B0B0B0;font-size:12px;text-align:center;padding-top:30px;">没有数据</p>
    </div>

    <!-- dialog -->
    <!-- <el-dialog :title="'控制器'+(controller.id?'编辑':'创建')" width="65%" :visible.sync="contorllerEditFlag"
      :close-on-click-modal="false">
      <div style="padding-right: 80px;">
        <el-form :model="controller" label-width="100px" class="zRowItems2">
          <z-form-item v-model="controller" :fields="fields1"></z-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click.native="submit1" :loading="submitLoading">
              确认
            </el-button>
            <el-button @click="contorllerEditFlag = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog> -->
    <el-dialog title="货位物料配置" width="75%" :visible.sync="shelfEditFlag" :close-on-click-modal="false">
      <div style="padding-right: 80px;">
        <el-form :model="shelf" label-width="100px" class="zRowItems3">
          <z-form-item :data="shelf" :fields="fields" :formProps="formProps"></z-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click.native="submit2" :loading="submitLoading">
              确认
            </el-button>
            <el-button @click="shelfEditFlag = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- <el-dialog title="批量绑定线别与工站" width="75%" :visible.sync="shelfConfigFlag" :close-on-click-modal="false">
      <div style="padding-right: 80px;">
        <el-form label-width="100px">
          <el-form-item label=" ">
            <div>您当前选择了 {{selectedList.length}} 个货位</div>
          </el-form-item>
          <el-form-item label="选择线别">
            <el-select v-model="config.line_id" style="width:100%;" clearable filterable>
              <el-option v-for="i in lineList" :key="i.value" :label="i.label" :value="i.value">
              </el-option>
            </el-select>
            <div>如果选择，则会将所有已选的货位绑定的线别都<b>&nbsp;修改&nbsp;</b>为此线别</div>
          </el-form-item>
          <el-form-item label="选择工站">
            <el-select v-model="config.group_id" style="width:100%;" clearable filterable>
              <el-option v-for="i in groupList" :key="i.value" :label="i.label" :value="i.value">
              </el-option>
            </el-select>
            <div>如果选择，则会给所有已选的货位都<b>&nbsp;增加&nbsp;</b>上此工站的绑定（已绑定的除外）</div>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click.native="submit3" :loading="submitLoading">
              确认
            </el-button>
            <el-button @click="shelfConfigFlag = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { arrayToObject, deepClone } from '@/utils'
import ZFormItem from '@/views/_common/form'
import commonMixin from '@/views/_common/mixin'

export default {
  components: { ZFormItem },
  mixins: [commonMixin],
  name: 'rackMatConf',
  data() {
    return {
      api: this.$api.rackshelf,
      busList: [{ value: 0 }, { value: 1 }, { value: 2 }, { value: 3 }],
      groupList: [],
      lineList: [],
      controllerList: [],
      controller_ip: null,
      controller: {},
      contorllerEditFlag: false,
      submitLoading: false,
      fields1: {
        ip_address: { label: 'IP', form: {} },
        port_id: { label: '端口', form: {} },
        enable_light: {
          label: '是否亮灯',
          form: { type: 'switch', activeValue: 1, inactiveValue: 0 },
        },
        connect_timeout: { label: '连接时限', form: { type: 'number' } },
        send_timeout: { label: '发送时限', form: { type: 'number' } },
        receive_timeout: { label: '接收时限', form: { type: 'number' } },
        input_ports_count: { label: '输入统计', form: { type: 'number' } },
        output_ports_cout: { label: '输出统计', form: { type: 'number' } },
        throttle_sleep_times: { label: '限流时长', form: { type: 'number' } },
        default_rs485_address: { label: '默认总线地址', form: { type: 'number' } },
      },
      shelfList: [],
      showShelfList: [],
      shelf: {},
      shelfEditFlag: false,
      selectAll: false,
      filter: {
        bus_id: null,
        line_id: null,
        group_id: null,
      },
      // fields2: {
      //   bus_id: { label: '控制器 ID', form: { disabled: true } },
      //   device_address: { label: '货位标签ID', form: { disabled: true } },
      //   ptldevice_type: { label: '设备类型', form: { disabled: true } },
      //   minor_type: { label: '最小类型', form: { disabled: true } },
      //   f1_color_after_press: { label: 'F1按压颜色', form: { disabled: true } },
      //   line_id: {
      //     label: '绑定线体',
      //     form: { type: 'select', options: {}, wholeRow: true, clearable: true, disabled: true },
      //   },
      //   groups: {
      //     label: '绑定工站',
      //     form: { type: 'select', options: {}, multiple: true, wholeRow: true, clearable: true, disabled: true },
      //   },
      //   stock_code: { label: '库位代码', form: { disabled: true } },
      //   material_id: {
      //     label: '存放物料',
      //     form: {
      //       placeholder: '输入料号或名称筛选',
      //       type: 'select',
      //       options: {},
      //       filterable: true,
      //       clearable: true,
      //       remote: true,
      //       wholeRow: true,
      //     },
      //   },

      //   material_qty: {
      //     label: '当前库存',
      //     form: {
      //       type: 'number',
      //       min: 0,
      //     },
      //   },
      //   safty_qty: {
      //     label: '安全库存',
      //     form: {
      //       type: 'number',
      //       min: 0,
      //     },
      //   },
      // },

      fields: [
        { title: '控制器 ID', key: 'bus_id', span: 12, props: { disabled: true } },
        { title: '货位标签ID', key: 'device_address', span: 12, props: { disabled: true } },
        { title: '设备类型', key: 'ptldevice_type', span: 12, props: { disabled: true } },
        { title: '最小类型', key: 'minor_type', span: 12, props: { disabled: true } },
        { title: 'F1按压颜色', key: 'f1_color_after_press', span: 12, props: { disabled: true } },
        {
          title: '绑定线体',
          key: 'line_id',
          name: 'select',
          span: 12,
          options: [],
          props: { disabled: true, clearable: true },
        },
        {
          title: '绑定工站',
          key: 'groups',
          span: 12,
          name: 'select',
          options: [],
          props: { disabled: true, clearable: true, multiple: true },
        },
        { title: '库位代码', key: 'stock_code', span: 12, props: { disabled: true } },
        {
          title: '存放物料',
          key: 'material_id',
          span: 12,
          name: 'select',
          options: [],
          props: {
            disabled: true,
            filterable: true,
            clearable: true,
            multiple: true,
            remote: true,
            remoteMethod: null,
          },
        },
        { title: '当前库存', key: 'material_qty', span: 12, name: 'number', props: { min: 0 } },
        { title: '安全库存', key: 'safty_qty', span: 12, name: 'number', props: { min: 0 } },
      ],
      config: {},
      shelfConfigFlag: false,
    }
  },
  methods: {
    init() {
      this.$request(this.$api.group + 'getlist', { mes_flag: 'Y' }).then((r) => {
        this.groupList = r.map((i) => ({ label: i.group_name, value: i.id ? i.id : i.group_code }))
        let tmp = {}
        this.groupList.forEach((i) => {
          tmp[i.value] = i.label
        })
        // this.fields2.groups.form.options = tmp
        this.getFieldConfig('groups').options = this.lineList
      })
      this.$request(this.$api.line + 'getlistbypage').then((r) => {
        this.lineList = r.list.map((i) => ({ label: i.line_name, value: i.id }))
        let tmp = {}
        this.lineList.forEach((i) => {
          tmp[i.value] = i.label
        })
        this.getFieldConfig('line_id').options = this.lineList
        // this.fields2.line_id.form.options = tmp
      })
      // this.fields2.material_id.form.remoteMethod = this.getMaOptions
      this.getFieldConfig('material_id').props.remoteMethod = this.getMaOptions
    },
    getList() {
      this.pageLoading = true
      this.$request(this.api + 'controller/list')
        .then((r) => {
          this.pageLoading = false
          this.controllerList = r.list
          this.controller_ip = null
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    // edit() {
    //   this.controller = {}
    //   if (this.controller_ip) {
    //     this.controller = { ...this.controllerList.find((i) => i.ip_address == this.controller_ip) }
    //   }
    //   this.contorllerEditFlag = true
    // },
    edit2() {
      this.shelf = { groups: [], controller_id: this.controllerList.find((i) => i.ip_address == this.controller_ip).id }
      if (this.selectedList.length > 1) {
        this.$message({
          message: '创建时不需选择货位，编辑时最多只能选择一个货位',
          type: 'error',
        })
        return
      } else if (this.selectedList.length == 1) {
        this.shelf = deepClone(this.selectedList[0])
        this.singleOption(this.shelf.material_id)
      }
      this.shelfEditFlag = true
    },
    // edit3() {
    //   if (this.selectedList.length == 0) {
    //     this.$message({
    //       message: '请至少选择一个货位',
    //       type: 'error',
    //     })
    //     return
    //   }
    //   this.config = {}
    //   this.shelfConfigFlag = true
    // },
    // submit1() {
    //   this.submitLoading = true
    //   delete this.controller.rowId
    //   this.$request(
    //     this.api + 'controller/add',
    //     this.controller,
    //     'post',
    //   )
    //     .then((r) => {
    //       this.submitLoading = false
    //       this.$message({
    //         message: '操作成功',
    //         type: 'success',
    //       })
    //       this.contorllerEditFlag = false
    //       this.controller_ip = null
    //       this.getList()
    //     })
    //     .catch(() => {
    //       this.submitLoading = false
    //     })
    // },
    submit2() {
      this.submitLoading = true
      let tmp = {
        shelf_id: this.shelf.id,
        material_id: this.shelf.material_id,
        material_qty: this.shelf.material_qty,
        safty_qty: this.shelf.safty_qty,
      }
      this.$request(this.api + 'configMat', tmp, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.shelfEditFlag = false
          this.getShelfList()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    // submit3() {
    //   this.submitLoading = true
    //   this.$request(
    //     this.api + 'config',
    //     {
    //         ids: this.selectedList.map((i) => i.id),
    //         group_id: this.config.group_id,
    //         line_id: this.config.line_id,
    //       },
    //     'post',
    //   )
    //     .then((r) => {
    //       this.submitLoading = false
    //       this.$message({
    //         message: '操作成功',
    //         type: 'success',
    //       })
    //       this.shelfConfigFlag = false
    //       this.getShelfList()
    //     })
    //     .catch(() => {
    //       this.submitLoading = false
    //     })
    // },
    // delete1() {
    //   if (!this.controller_ip) {
    //     this.$message({
    //       message: '请先选择控制器',
    //       type: 'error',
    //     })
    //     return
    //   }
    //   let id = this.controllerList.find((i) => i.ip_address == this.controller_ip).id
    //   this.$confirm('确定要删除这个控制器？', '操作确认').then(() => {
    //     this.pageLoading = true
    //     this.$request(this.api + 'controller/delete', { id }, 'post')
    //       .then((r) => {
    //         this.pageLoading = false
    //         this.$message({
    //           message: '操作成功',
    //           type: 'success',
    //         })
    //         this.getList()
    //       })
    //       .catch(() => {
    //         this.pageLoading = false
    //       })
    //   })
    // },
    // delete2() {
    //   if (this.selectedList.length == 0) {
    //     this.$message({
    //       message: '请先选择货位',
    //       type: 'error',
    //     })
    //     return
    //   }
    //   this.$confirm(`确定要删除选择的 ${this.selectedList.length} 个货位？`, '操作确认').then(() => {
    //     this.pageLoading = true
    //     this.$request(this.api + 'delete', { ids: JSON.stringify(this.selectedList.map((i) => i.id)) }, 'post')
    //       .then((r) => {
    //         this.pageLoading = false
    //         this.$message({
    //           message: '操作成功',
    //           type: 'success',
    //         })
    //         this.getShelfList()
    //       })
    //       .catch(() => {
    //         this.pageLoading = false
    //       })
    //   })
    // },
    controllerChange() {
      this.filter = {}
      this.getShelfList()
    },
    // selectAllChange() {
    //   if (this.selectAll) {
    //     this.shelfList.forEach((i) => {
    //       i.selected = true
    //     })
    //   } else {
    //     this.shelfList.forEach((i) => {
    //       i.selected = false
    //     })
    //   }
    // },
    filterShowList() {
      this.showShelfList = this.shelfList.filter((i) => {
        return (
          ((!this.filter.bus_id && this.filter.bus_id !== 0) || i.bus_id == this.filter.bus_id) &&
          (!this.filter.line_id || i.line_id == this.filter.line_id) &&
          (!this.filter.group_id || i.groups.indexOf(this.filter.group_id) != -1)
        )
      })
    },
    getShelfList() {
      console.log('this.controller_ip', this.controller_ip)
      if (!this.controller_ip) return
      let cid = this.controllerList.find((i) => i.ip_address == this.controller_ip).id
      this.pageLoading = true
      this.$request(this.api + 'getlist', {
        controller_id: cid,
      })
        .then((r) => {
          this.pageLoading = false
          this.shelfList = r.list.map((i) => {
            i.selected = false
            i.groups = i.groups ? i.groups.split(',') : []
            return i
          })
          this.filterShowList()
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    selectedChange(v) {
      this.shelfList.forEach((i) => {
        i.selected = i.id == v.id
      })
    },
    getMaOptions(query) {
      if (query) {
        this.$request(this.$api.mat + 'getmatandsku', {
          queryString: query,
        })
          .then((r) => {
            this.setFieldOptions('material_id', r, 'id', ['key_part_no', 'key_part_name'])
            // this.fields2.material_id.form.options = arrayToObject(r, 'id', ['key_part_no', 'key_part_name'])
          })
          .catch(() => {})
      } else {
        // this.fields2.material_id.form.options = {}
        this.setFieldOptions('material_id', [])
      }
    },
    singleOption(val) {
      if (val) {
        this.$request(this.$api.mat + 'getmatandsku', {
          id: val,
        })
          .then((r) => {
            // this.fields2.material_id.form.options = arrayToObject(r, 'id', ['key_part_no', 'key_part_name'])
            this.setFieldOptions('material_id', r, 'id', ['key_part_no', 'key_part_name'])
          })
          .catch(() => {})
      } else {
        // this.fields2.material_id.form.options = {}
        this.setFieldOptions('material_id', [])
      }
    },
  },
  computed: {
    selectedList: function () {
      return this.showShelfList.filter((i) => i.selected)
    },
  },
  created: function () {
    this.init()
    this.getList()
  },
}
</script>

<style lang="scss" scoped>
::v-deep.el-divider {
  margin: 10px 0;
}
.card {
  display: inline-block;
  padding: 8px;
  border: 1px solid #aaaaaa;
  border-radius: 4px;
  width: 120px;
  height: 55px;
  margin: 0 5px 5px 0;
  overflow: hidden;
}
.card.checked {
  border: 1px solid rgb(64, 158, 255);
}
.card .info {
  margin-top: 5px;
  font-size: 12px;
  color: #999999;
  white-space: nowrap;
  overflow: hidden;
}
</style>